﻿using Basic.FormModel.DB;
using Basic.FormRemoteModel.FormView.Model;
using WeDonekRpc.Client;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.SqlSugar;
using WeDonekRpc.SqlSugar.VirtualQuery;

namespace Basic.FormDAL.Repository
{
    internal class FormViewDAL : BasicDAL<DBFormView, long>, IFormViewDAL
    {
        private readonly IAgentFormDBTools _dbTools;

        public FormViewDAL ( IRepository<DBFormView> basicDAL, IAgentFormDBTools tools ) : base(basicDAL, "view")
        {
            this._dbTools = tools;
        }
        public long Add ( FormViewAdd data )
        {
            DBFormView add = data.ConvertMap<FormViewAdd, DBFormView>();
            add.Id = IdentityHelper.CreateId();
            add.IsGenerate = false;
            this._BasicDAL.Insert(add);
            return add.Id;
        }
        public void Delete ( DBFormView source, string name )
        {
            ISqlQueue<DBFormView> queue = this._BasicDAL.BeginQueue();
            queue.Delete(a => a.Id == source.Id);
            queue.DeleteBy<DBFormViewCol>(c => c.FormId == source.FormId);
            if ( source.IsGenerate )
            {
                using ( ILocalTransaction tran = this._BasicDAL.ApplyTran() )
                {
                    _ = queue.Submit();
                    _ = this._dbTools.DropView(name);
                    tran.Commit();
                }
            }
            else
            {
                _ = queue.Submit();
            }
        }
        public void GenerateView ( DBFormView sour, string name, QueryStruct body )
        {
            if ( sour.IsGenerate )
            {
                this._dbTools.EditView(name, body);
            }
            else
            {
                using ( ILocalTransaction tran = this._BasicDAL.ApplyTran() )
                {
                    if ( base._BasicDAL.Update(a => a.IsGenerate == true, a => a.Id == sour.Id && a.IsGenerate == false) )
                    {
                        this._dbTools.EditView(name, body);
                        tran.Commit();
                    }
                }
            }
        }
    }
}
